package io.potato.ts.repository;

import io.potato.ts.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

/**
 * 用户表(t_user)数据访问接口
 * 
 * @author timl
 *
 * <p>2019-01-07 15:13:58</p>
 */
public interface UserRepository extends JpaRepository<User, Integer> {
	
	User findByUserCode(String userCode);
	
	User findByUserName(String userName);
	
	@Query("select id from User where userCode = :userCode")
	Integer findIdByCode(@Param("userCode") String userCode);

	@Query("select smsSign from User where userCode = :userCode")
	String findSignByCode(@Param("userCode") String userCode);
	
	@Query(value = "select real_name from t_user where mobile_no = :mobileNo limit 1", nativeQuery = true)
	String findNameByMobileNo(String mobileNo);
	
	@Modifying
	@Query(value = "update User set locked = :locked where id in (:ids)")
	int updateLockStatus(@Param("ids") List<Integer> ids, @Param("locked") Integer locked);
	
	@Modifying
	@Query(value = "update User set smsSign = :smsSign, realName = :smsSign where id = :id")
	int updateSmsSign(@Param("id") Integer id, @Param("smsSign") String smsSign);

	@Modifying
    @Query(nativeQuery = true, value = "update t_user set last_login = now(), login_count = login_count + 1 where id = :id")
	int updateLastLogin(@Param("id") Integer id);
	
	@Modifying
	@Query(value = "update User set password = :password, need_modify = 0, last_modify = now()  where id = :id")
	int updatePassword(@Param("id") Integer id, @Param("password") String password);

	List<User> findByOrganIdOrderByRealNameAsc(Integer organId);

    @Query(value = "select t.* from t_user t join t_user_group_link t2 on t.id = t2.user_id WHERE t.organ_id = :organId AND t2.group_id IN (:userGroupId) order by t.real_name", nativeQuery = true)
	List<User> findByGroupId(@Param("userGroupId") List<Integer> userGroupId, @Param("organId") Integer organId);

    @Query(nativeQuery = true, value = "select max(user_code) from t_user where user_type = 2")
    String findMaxWebUserCode();

	@Query(nativeQuery = true, value = "select max(user_code) from t_user where user_type <> 2 or user_type is null")
	String findMaxApiUserCode();

	@Query(value="from User where deptId in (:deptIds)")
	List<User> findByDeptIds(@Param("deptIds") Integer[] deptIds);

	Long countByOrganId(@Param("organId") Integer organId);

}
